/*
 * map_creator.c
 */

#include <stdio.h>
#include "map_creator.h"

static FILE *current_map = NULL;

/*
 * Returns 1 iff the given map name exists and is readable.
 */
int map_exists( const char *name ) {
    FILE *fp;
    if( fp = fopen(name, "rb") ) {
        fclose(fp);
        return 1;
    }
    else {
        return 0;
    }
}

/*
 * Creates a new map file of the given name with the given dimensions. If a map
 * with that name already exists, the function fails and returns 1.
 */
int create_map( const char *name, unsigned int height, unsigned int width ) {
    struct map_header header;
    if( current_map == NULL ) {
        if( current_map = fopen(name, "rb") ) {
            /* TODO: error */
            fclose(current_map);
            return 1;
        }
        current_map = fopen(name, "wb");
        if( current_map != NULL ) {
            header.height = height;
            header.width = width;
            fwrite( &header, sizeof(struct map_header), 1, current_map );
        }
    }
    return 0;
}

/*
 * Write the given tile to the current map.
 */
int write_tile( struct map_tile *t ) {
    /* TODO: Make a tile buffer to reduce the number of fwrite calls. */
    /* TODO: Check that there currently is a map. */
    if( fwrite( t, sizeof(struct map_tile), 1, current_map ) ) {
        return 0;
    }
    return -1;
}

/*
 * Close the current map.
 */
int close_map() {
    return fclose(current_map);
}

/*
 * Checks to see if maps/testmap.rgm exists, and if it doesn't, creates it.
 * Test Map is a 50x50 map of even surfaced tiles of the same type (grass).
 */
int create_test_map() {
    /* TODO: This is ugly, and possibly unnecessary. */
    struct map_tile tile; /* They're all the same, so only need one. */
    int i;
    FILE *f;
    if( f = fopen("maps/testmap.rgm", "rb") ) {
        fclose(f);
        return 0;
    }
    else {
        if( create_map("maps/testmap.rgm", 50, 50) ) {
            fprintf( stderr, "ERROR: Failed to create test map!\n" );
            return -1;
        }
        else {
            tile.type = 0;
            tile.altitude = 0;
            /* 50x50 map = 2500 tiles */
            for( i = 0; i < 2500; i++ ) {
                write_tile(&tile);
            }
            close_map();
            return 0;
        }
    }
}
